package cn.lastjune.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.lastjune.pojo.Case;
import cn.lastjune.pojo.Mission;
import cn.lastjune.pojo.Problem;
import cn.lastjune.service.CaseService;
import cn.lastjune.service.DomaindeptService;
import cn.lastjune.service.MissionService;
import cn.lastjune.util.NumberUtil;
import cn.lastjune.util.Page;

@Controller
@RequestMapping("/casecon")
public class CaseController
{
    @Autowired
    CaseService caseService;
    @Autowired
    MissionService missionService;
    @Autowired
    DomaindeptService domaindeptService;

    public String emptyJson = "{metaData:{totalProperty : 'total',root : "
            + "'result',fields: ['recdispnum', 'tasknum', " + "'recordtype','recordprocessstate', 'reportpatrol',"
            + " 'verifypatrol','examinepatrol', 'acceptoperator'," + "'accreditationdutyperson', 'dispatchor',"
            + "'seconddispatchor', 'inspectior'," + " 'examineoperator','closepeople', "
            + "'eventurgen', 'disposedeadline'," + "'disposedate', 'delaytimes', 'overtimemultiple"
            + "','acceptstarttime', 'acceptendtime','registerstarttime',"
            + " 'registerendtime','endcasestarttime', 'endcaseendtime',"
            + " 'endcasetime','postponedtime', 'abandontime'," + " 'workingstaff','workingdept', 'backstarttime',"
            + " 'postpinedtype','onticktype', 'delaytype', 'patrolid','domaindeptID']}," + "total:0, result : []}";

    @RequestMapping(method = RequestMethod.GET)
    public void getAll(HttpServletRequest request, HttpServletResponse response) throws IOException
    {
        PrintWriter out = response.getWriter();
        final Page<Case> page = new Page<Case>();
        int start=request.getParameter("start")==null?0:NumberUtil.parseInt(request.getParameter("start"));
        int limit=request.getParameter("limit")==null?11:NumberUtil.parseInt(request.getParameter("limit"));
        page.setPageNo(start/limit+1);
        page.setPageSize(limit);
        final Page<Case> result = caseService.getAllCase(page);
        final List<Case> list = result.getResult();
        StringBuilder sb = new StringBuilder();
        int count = list.size();
        if (count > 0)
        {
            String jsonHead = "{" + "metaData:{" + "totalProperty : 'total'," + "root : 'result',"
                    + "fields: ['recdispnum', 'tasknum', " + "'recordtype','recordprocessstate', 'reportpatrol',"
                    + " 'verifypatrol','examinepatrol', 'acceptoperator'," + "'accreditationdutyperson',"
                    + " 'dispatchor'," + "'seconddispatchor', 'inspectior'," + " 'examineoperator','closepeople', "
                    + "'eventurgen', 'disposedeadline'," + "'disposedate', 'delaytimes', 'overtimemultiple"
                    + "','acceptstarttime', 'acceptendtime','registerstarttime',"
                    + " 'registerendtime','endcasestarttime', 'endcaseendtime',"
                    + " 'endcasetime','postponedtime', 'abandontime',"
                    + " 'workingstaff','workingdept', 'backstarttime',"
                    + " 'postpinedtype','onticktype', 'delaytype', 'patrolid','domaindeptID']}," + "total:"
                    + result.getTotalCount() + ", result : [";
            sb.append(jsonHead);

            for (Case e : list)
            {
                count--;
                sb.append("{recdispnum:'" + e.getRecdispnum() + "',tasknum:'"
                        + e.getMission().getTasknum().replace("\n", "") + "',acttimestateID:'" + e.getActtimestateid()
                        + "',recordtype:'" + e.getRecordtype() + "',recordprocessstate:'" + e.getRecordprocessstate()
                        + "',reportpatrol:'" + e.getReportpatrol() + "',verifypatrol:'" + e.getVerifypatrol()
                        + "',examinepatrol:'" + e.getExaminepatrol() + "',acceptoperator:'" + e.getAcceptoperator()
                        + "',accreditationdutyperson:'" + e.getAccreditationdutyperson() + "',dispatchor:'"
                        + e.getDispatchor() + "',seconddispatchor:'" + e.getSeconddispatchor() + "',inspectior:'"
                        + e.getInspectior() + "',examineoperator:'" + e.getExamineoperator() + "',closepeople:'"
                        + e.getClosepeople() + "',eventurgen:'" + e.getEventurgen() + "',disposedeadline:'"
                        + e.getDisposedeadline() + "',disposedate:'" + e.getDisposedate() + "',delaytimes:'"
                        + e.getDelaytimes() + "',overtimemultiple:'" + e.getOvertimemultiple() + "',acceptstarttime:'"
                        + e.getAcceptoperator() + "',acceptendtime:'" + e.getAcceptendtime() + "',registerstarttime:'"
                        + e.getRegisterstarttime() + "',registerendtime:'" + e.getRegisterendtime()
                        + "',endcasestarttime:'" + e.getEndcasestarttime() + "',endcaseendtime:'"
                        + e.getEndcaseendtime() + "',endcasetime:'" + e.getEndcasetime() + "',postponedtime:'"
                        + e.getPostponedtime() + "',abandontime:'" + e.getAbandontime() + "',workingstaff:'"
                        + e.getWorkingstaff() + "',workingdept:'" + e.getWorkingdept() + "',backstarttime:'"
                        + e.getBackstarttime() + "',postpinedtype:'" + e.getPostpinedtype() + "',onticktype:'"
                        + e.getOnticktype() + "',delaytype:'" + e.getDelaytype() + "',patrolid:'" + e.getPatrolid()
                        + "',domaindeptID:'" + ""+ "'}");
                if (count > 0)
                {
                    sb.append(",");
                }
            }
            sb.append("]}");
            System.out.println(sb);
        }
        else
        {
            sb.append(emptyJson);
        }
        String sbnew = sb.toString().replace("null", "");
        out.print(sbnew);
        out.flush();
    }

    @RequestMapping(method = RequestMethod.POST)
    public void modifyCase(HttpServletRequest request, HttpServletResponse response) throws IOException
    {
        PrintWriter out = response.getWriter();
        response.setHeader("Charset", "UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        response.setContentType("text/json"); // 解决后台数据中文乱码
        response.setCharacterEncoding("UTF-8");
        String method = request.getParameter("method");
        String recdispnum = request.getParameter("recdispnum");
        String tasknum = request.getParameter("tasknum");
        String problemID = request.getParameter("problemID");
        String recordtype = request.getParameter("recordtype");
        String recordprocessstate = request.getParameter("recordprocessstate");
        String reportpatrol = request.getParameter("reportpatrol");
        String verifypatrol = request.getParameter("verifypatrol");
        String examinepatrol = request.getParameter("examinepatrol");
        String acceptoperator = request.getParameter("acceptoperator");
        String accreditationdutyperson = request.getParameter("accreditationdutyperson");
        String dispatchor = request.getParameter("dispatchor");
        String seconddispatchor = request.getParameter("seconddispatchor");
        String inspectior = request.getParameter("inspectior");
        String examineoperator = request.getParameter("examineoperator");
        String closepeople = request.getParameter("closepeople");
        String eventurgen = request.getParameter("eventurgen");
        String disposedeadline = request.getParameter("disposedeadline");
        String disposedate = request.getParameter("disposedate");
        String delaytimes = request.getParameter("delaytimes");
        String overtimemultiple = request.getParameter("overtimemultiple");
        String acceptstarttime = request.getParameter("acceptstarttime");
        String acceptendtime = request.getParameter("acceptendtime");
        String registerstarttime = request.getParameter("registerstarttime");
        String registerendtime = request.getParameter("registerendtime");
        String endcasestarttime = request.getParameter("endcasestarttime");
        String endcaseendtime = request.getParameter("endcaseendtime");
        String endcasetime = request.getParameter("endcasetime");
        String postponedtime = request.getParameter("postponedtime");
        String abandontime = request.getParameter("abandontime");
        String workingstaff = request.getParameter("workingstaff");
        String workingdept = request.getParameter("workingdept");
        String backstarttime = request.getParameter("backstarttime");
        String postpinedtype = request.getParameter("postpinedtype");
        String onticktype = request.getParameter("onticktype");
        String delaytype = request.getParameter("delaytype");
        String patrolid = request.getParameter("patrolid");
        String domaindeptid = request.getParameter("domaindeptID");
        Case e = new Case();
        e.setRecdispnum(recdispnum);
        e.setMission(missionService.getMissionById(tasknum));
        // e.setproblemID(problemID);
        e.setRecordtype(recordtype);
        e.setMission((Mission) missionService.getMissionById(tasknum));
        e.setRecordprocessstate(recordprocessstate);
        e.setReportpatrol(reportpatrol);
        e.setVerifypatrol(verifypatrol);
        e.setExaminepatrol(examinepatrol);
        e.setAcceptoperator(acceptoperator);
        e.setAccreditationdutyperson(accreditationdutyperson);
        e.setDispatchor(dispatchor);
        e.setSeconddispatchor(seconddispatchor);
        e.setInspectior(inspectior);
        e.setExamineoperator(examineoperator);
        e.setClosepeople(closepeople);
        e.setEventurgen(eventurgen);
        e.setDisposedeadline(new Date(!disposedeadline.equals("") ? acceptstarttime.toString() : "01/01/1990"));
        e.setDisposedate(new Date(!disposedate.equals("") ? disposedate.toString() : "01/01/1990"));
        e.setDelaytimes(new BigDecimal(!delaytimes.equals("") ? "0.0" : delaytimes.toString()));
        e.setOvertimemultiple(new BigDecimal(!overtimemultiple.equals("") ? "0.0" : overtimemultiple));
        e.setAcceptstarttime(new Date(!acceptstarttime.equals("") ? acceptstarttime.toString() : "01/01/1990"));
        e.setAcceptendtime(new Date(!acceptendtime.equals("") ? acceptendtime.toString() : "01/01/1990"));
        e.setRegisterstarttime(new Date(!registerstarttime.equals("") ? registerstarttime.toString() : "01/01/1990"));
        e.setRegisterendtime(new Date(!registerendtime.equals("") ? registerendtime.toString() : "01/01/1990"));
        e.setEndcasestarttime(new Date(!endcasestarttime.equals("") ? registerendtime.toString() : "01/01/1990"));
        e.setEndcaseendtime(new Date(!endcaseendtime.equals("") ? endcaseendtime.toString() : "01/01/1990"));
        e.setEndcasetime(new Date(!endcasetime.equals("") ? endcasetime.toString() : "01/01/1990"));
        e.setPostponedtime(new Date(!postponedtime.equals("") ? postponedtime.toString() : "01/01/1990"));
        e.setAbandontime(new Date(!abandontime.equals("") ? abandontime.toString() : "01/01/1990"));
        e.setWorkingstaff(workingstaff);
        e.setWorkingdept(workingdept);
        e.setBackstarttime(new Date(!backstarttime.equals("") ? backstarttime.toString() : "01/01/1990"));
        e.setPostpinedtype(new BigDecimal((postpinedtype.equals("") ? "0.0" : postpinedtype.toString())));
        e.setOnticktype(new BigDecimal(onticktype == "" ? "0.0" : onticktype.toString()));
        e.setDelaytype(new BigDecimal(delaytype == "" ? "0.0" : delaytype.toString()));
        e.setPatrolid(patrolid);
        e.setDomaindept(domaindeptService.getDomaindeptById(new BigDecimal(domaindeptid.equals("") ? "0.0"
                : domaindeptid.toString())));
        System.out.println(method);

        if ("add".equals(method))
        {
            try
            {
                caseService.insertCase(e);
                out.print("{success:true,msg:\'yes\'}");
                out.flush();
                return;
            }
            catch (Exception e2)
            {
                out.print("{success:false,msg:\'no\'},{failure:true}");
                out.flush();
                return;
            }

        }
        if ("edit".equals(method))
        {
            try
            {
                caseService.updateCase(e);
                out.print("{success:true,msg:\'yes\'}");
                out.flush();
                return;
            }
            catch (Exception e2)
            {
                out.print("{success:false,msg:\'no\'},{failure:true}");
                out.flush();
                return;
            }
        }
        if ("delete".equals(method))
        {
            try
            {
                String ids[] = request.getParameterValues("ids");
                for (String id : ids)
                {
                    caseService.deleteCase(id);
                }
                out.print("{success:true,msg:\'yes\'}");
                out.flush();
                return;
            }
            catch (Exception e2)
            {
                out.print("{success:false,msg:\'no\'},{failure:true}");
                out.flush();
                return;
            }
        }
    }

    @RequestMapping(method = RequestMethod.OPTIONS)
    public void complicated(HttpServletRequest request, HttpServletResponse response) throws IOException
    {
        PrintWriter out = response.getWriter();
    }
}
